<template>
  <el-card header="消息公开">
    <div class="box">
      <div class="box-tab">
        <div class="box-tab-search">
          <div>
            <span>按年份</span>
            <el-date-picker
              v-model="params.year"
              valueFormat="YYYY"
              type="year"
              placeholder="请选择"
              class="select"
              style="flex: 1"
              @change="reload"
            />
          </div>
          <!--<div>-->
          <!--  <span>来源</span>-->
          <!--  <MSelect-->
          <!--    v-model="params.dataSource"-->
          <!--    placeholder="请选择"-->
          <!--    :options="dataSourceOptions"-->
          <!--    class="select"-->
          <!--    @change="reload"-->
          <!--    clearable-->
          <!--  />-->
          <!--</div>-->
        </div>
        <el-scrollbar
          ref="scrollbarRef"
          @scroll="handleScroll"
          class="scrollbar"
        >
          <div class="box-tab-list">
            <div
              :class="
                tabListValue === it.sorgResultPublicityId
                  ? 'box-tab-list-item box-tab-list-item-ac'
                  : 'box-tab-list-item'
              "
              v-for="it in tabList"
              :key="it.sorgResultPublicityId"
              @click="setTabList(it.sorgResultPublicityId)"
            >
              <div class="box-tab-list-item-title">
                {{ it.title }}
              </div>
              <div class="box-tab-list-item-time">{{ it.createTime }}</div>
            </div>
          </div>
        </el-scrollbar>
        <div class="box-tab-add">
          <div @click="add(0)" v-if="$checkAuth('informationDisclosureAdd')">
            新增公开信息
          </div>
        </div>
      </div>
      <div class="box-content">
        <div class="box-content-header">
          <div class="box-content-header-title">公开文章</div>
          <div class="box-content-header-btns">
            <!--<el-button-->
            <!--  type="primary"-->
            <!--  v-if="detailInfoOld.state != 2 && isEdit === 1"-->
            <!--  @click="saveTheDraft"-->
            <!--  >保存草稿</el-button-->
            <!--&gt;-->
            <el-button
              type="primary"
              v-if="isEdit === 0 && $checkAuth('informationDisclosureEdit')"
              @click="setIsEdit"
              >编辑</el-button
            >
            <el-button
              type="primary"
              v-if="isEdit === 1 && $checkAuth('informationDisclosureSave')"
              @click="save"
              >保存</el-button
            >

            <el-button
              type="primary"
              @click="publish"
              v-if="isEdit === 0 && $checkAuth('informationDisclosurePublish')"
              >发布</el-button
            >
            <el-button
              @click="generateLedgers"
              v-if="$checkAuth('informationDisclosureExport')"
              >导出</el-button
            >
          </div>
        </div>
        <div class="content">
          <el-row
            :gutter="20"
            style="margin: 0; padding: 0; border: 1px solid #e9e9e9"
          >
            <el-col :span="12">
              <div class="info">
                <div class="info-label">发布机构</div>
                <div class="info-input">
                  <!--<MTreeSelect-->
                  <!--  v-model="form.org"-->
                  <!--  placeholder="请选择"-->
                  <!--  :data="orgData"-->
                  <!--  :fields="{-->
                  <!--    value: 'deptName',-->
                  <!--    label: 'deptName',-->
                  <!--    children: 'children'-->
                  <!--  }"-->
                  <!--  style="width: 100%"-->
                  <!--  :check-strictly="true"-->
                  <!--  v-if="isEdit === 1"-->
                  <!--/>-->
                  <el-tree-select
                    v-model="form.org"
                    :data="orgData"
                    :props="{
                      value: 'deptName',
                      label: 'deptName',
                      children: 'children'
                    }"
                    :check-strictly="true"
                    placeholder="请选择"
                    filterable
                    style="width: 100%"
                    v-if="isEdit === 1"
                  ></el-tree-select>
                  <span v-else>{{ detailInfo.org || '' }}</span>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info">
                <div class="info-label">成文日期</div>
                <div class="info-input">{{ detailInfo.createTime || '' }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info">
                <div class="info-label">发布日期</div>
                <div class="info-input">{{ detailInfo.releaseTime || '' }}</div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="info">
                <div class="info-label">
                  标&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;题
                </div>
                <div class="info-input">
                  <ElInput
                    v-model="form.title"
                    placeholder="请输入"
                    style="width: 100%"
                    v-if="isEdit === 1"
                  />
                  <span v-else>{{ detailInfo.title || '' }}</span>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info">
                <div class="info-label">发文字号</div>
                <div class="info-input">
                  <ElInput
                    v-model="form.documentNum"
                    placeholder="请输入"
                    style="width: 100%"
                    v-if="isEdit === 1"
                  />
                  <span v-else>{{ detailInfo.documentNum || '' }}</span>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info">
                <div class="info-label">有&nbsp;效&nbsp;性</div>
                <div class="info-input">
                  <ElInput
                    v-model="form.effective"
                    placeholder="请输入"
                    style="width: 100%"
                    v-if="isEdit === 1"
                  />
                  <span v-else>{{ detailInfo.effective || '' }}</span>
                </div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="info">
                <div class="info-label">佐证材料</div>
                <div class="info-input">
                  <MBackingMaterial
                    v-model="form.files"
                    dateFormat="YYYY-MM-DD HH:mm"
                    v-if="isEdit === 1"
                  />
                  <PreviewFile :tableData="detailInfo.files" v-else />
                </div>
              </div>
            </el-col>
          </el-row>
          <div class="table" v-if="detailInfo.source === 1">
            <div class="table-title">
              {{ detailInfo.title }}
            </div>
            <table>
              <thead>
                <tr>
                  <td width="4%">序号</td>
                  <td width="56%">抽查对象名称</td>
                  <td width="20%">抽查时间</td>
                  <td width="20%">检查方式</td>
                  <!--<td width="15%">执法检查信息</td>-->
                  <!--<td width="15%">处理情况</td>-->
                  <!--<td width="15%">是否已整改</td>-->
                </tr>
              </thead>
              <tbody>
                <tr v-for="(it, index) in detailInfo.detailDO">
                  <td>{{ index + 1 }}</td>
                  <td>{{ it.orgName }}</td>
                  <td>{{ getTime(it.spotCheckTime, it.spotCheckEndTime) }}</td>
                  <td>{{ it.orgFrom }}</td>
                  <!--<td>-->
                  <!--  <el-input-->
                  <!--    placeholder="请输入"-->
                  <!--    v-model="it.law"-->
                  <!--    v-if="isEdit === 1"-->
                  <!--  />-->
                  <!--  <span v-else>{{ it.law }}</span>-->
                  <!--</td>-->
                  <!--<td>-->
                  <!--  <el-input-->
                  <!--    placeholder="请输入"-->
                  <!--    v-model="it.handle"-->
                  <!--    v-if="isEdit === 1"-->
                  <!--  />-->
                  <!--  <span v-else>{{ it.handle }}</span>-->
                  <!--</td>-->
                  <!--<td>-->
                  <!--  <MSelect-->
                  <!--    placeholder="请选择"-->
                  <!--    :options="[-->
                  <!--      {-->
                  <!--        label: '是',-->
                  <!--        value: 1-->
                  <!--      },-->
                  <!--      {-->
                  <!--        label: '否',-->
                  <!--        value: 0-->
                  <!--      }-->
                  <!--    ]"-->
                  <!--    style="width: 100%"-->
                  <!--    v-model="it.rectFlag"-->
                  <!--    v-if="isEdit === 1"-->
                  <!--  />-->
                  <!--  <span v-else>{{ it.rectFlag === 0 ? '否' : '是' }}</span>-->
                  <!--</td>-->
                </tr>
              </tbody>
            </table>
          </div>
          <div v-if="detailInfo.source === 0" style="padding-bottom: 30px">
            <div style="padding: 30px 0">内容描述</div>
            <m-rich-editor
              v-model="form.describes"
              v-if="isEdit == 1"
            ></m-rich-editor>
            <div v-else v-html="detailInfo.describes"></div>
          </div>
        </div>
      </div>
    </div>
  </el-card>
  <AddForm ref="AddFormRef" @reload="reload" />
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import PreviewFile from '@/views/spotCheck/components/previewFile/previewFile.vue'
import AddForm from './components/addForm/addForm.vue'
import {
  msgAddOrUpd,
  msgDetail,
  msgDraft,
  msgLedger,
  msgLeftList,
  msgRelease,
  soptCheckLedger
} from '@/api/spotCheck/spotCheck'
import { newDeptTreeInfoAll } from '@/api/systemSetting/personnel'
import { dateFormat } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
const route = useRoute()
const value = ref('')

onMounted(() => {
  newDeptTreeInfoAll().then((res: any) => {
    orgData.value = res.data
  })
  if (route.query?.id) {
    params.value.sorgResultPublicityId = route.query.id
    reload()
    return
  }

  if (route.query?.sorgSpotCheckPlanId) {
    params.value.sorgSpotCheckPlanId = route.query.sorgSpotCheckPlanId
    reload()
    return
  }
  reload()
})
const getTime = (n, m) => {
  if (n && m) {
    return n + '至' + m
  } else if (n) {
    return n
  } else if (m) {
    return m
  } else {
    return ''
  }
}
const params = ref({
  year: undefined,
  dataSource: undefined,
  pageNum: 1,
  pageSize: 20,
  sorgResultPublicityId: undefined,
  sorgSpotCheckPlanId: undefined
})

const scrollbarRef = ref(null)
let isScrollBottomHandled = false // 标志位，用于控制是否已经处理了滚动到底部事件

const handleScroll = () => {
  if (isScrollBottomHandled) {
    return // 如果已经处理过滚动到底部事件，直接返回，避免重复触发
  }
  const el = scrollbarRef.value.$el // 获取 el-scrollbar 组件的 DOM 元素
  const container = el.querySelector('.el-scrollbar__wrap') // 获取 el-scrollbar 的容器元素
  const scrollBottom = container.scrollTop + container.clientHeight
  const scrollHeight = container.scrollHeight

  // 判断是否接近底部
  if (scrollBottom >= scrollHeight - 10) {
    // 这里的 10 可以根据实际情况调整
    console.log('滚动到了底部')
    // 执行滚动到底部后的操作
    // 设置标志位为 true，表示已经处理过滚动到底部事件
    isScrollBottomHandled = true
    params.value.pageNum++
    init()
  }
}

//去掉重复数据
function removeDuplicates(arr) {
  const seen = new Map()
  return arr.filter((item) => {
    if (!seen.has(item.sorgResultPublicityId)) {
      seen.set(item.sorgResultPublicityId, true)
      return true
    }
    return false
  })
}

const tabList = ref([])
const tabListValue = ref('')
const init = async (type) => {
  const res = await msgLeftList(params.value)
  res.data.list = removeDuplicates(res.data.list)
  if (res.data.total > params.value.pageNum * params.value.pageSize) {
    isScrollBottomHandled = false
  }
  if (params.value.pageNum === 1) {
    tabList.value = res.data.list
    if (res.data.list.length > 0) {
      tabListValue.value = res.data.list[0].sorgResultPublicityId
    }
  } else {
    tabList.value = [...tabList.value, ...res.data.list]
  }
  if (type) {
    await reloadDetail()
  }
  return res
}

const yearChange = () => {
  reload()
}

const detailInfo = ref('')
watch(
  () => tabListValue.value,
  (val) => {
    console.log('val', val)
    reloadDetail()
  }
)

//详情
const detailInfoOld = ref('')
const reloadDetail = async () => {
  const res = await msgDetail({ sorgResultPublicityId: tabListValue.value })
  detailInfoOld.value = JSON.parse(JSON.stringify(res.data))
  if (res.data?.draft) {
    detailInfo.value = JSON.parse(res.data.draft)
    detailInfo.value.source = res.data.source
    detailInfo.value.createTime = res.data.createTime
    detailInfo.value.releaseTime = res.data.releaseTime
    //detailInfo.value.detailDO = res.data.detailDO
  } else {
    detailInfo.value = res.data
  }
  if (detailInfo.value?.title) {
    detailInfo.value.title = detailInfo.value.title.replace(
      '抽查名单及结果公示',
      ''
    )
  }
  setForm()
  console.log('detailInfo.value', detailInfo.value)
}

const setIsEdit = () => {
  isEdit.value = isEdit.value === 1 ? 0 : 1
  setForm()
}

const setForm = () => {
  if (
    Array.isArray(detailInfo.value.files) &&
    detailInfo.value.files.length > 0
  ) {
    form.files = detailInfo.value.files.map((i) => ({
      fileSum: i.filePage,
      isSave: true,
      name: i.fileName,
      createdAt: dateFormat(i.createdAt, 'YYYY-MM-DD'),
      file: [
        {
          name: i.fileName,
          status: 'success',
          url: i.fileUrl
        }
      ]
    }))
  } else {
    form.files = []
  }
  form.title = detailInfo.value.title
  form.documentNum = detailInfo.value.documentNum
  form.describes = detailInfo.value.describes
  form.effective = detailInfo.value.effective
  form.dataSource = detailInfo.value.dataSource
  form.year = detailInfo.value.year
  //这里处理发布机构
  form.org = detailInfo.value.org
}

const reload = () => {
  params.value.pageNum = 1
  init()
}

const setTabList = (id) => {
  tabListValue.value = id
  isEdit.value = 0
}
//新增
const AddFormRef = ref()
const add = (id = 0) => {
  AddFormRef.value.show(id)
}

const isEdit = ref(0)

const dataSourceOptions = ref([
  {
    label: '合格组织抽查',
    value: 0
  },
  {
    label: '风险异常组织抽查',
    value: 1
  },
  {
    label: '社会组织抽查',
    value: 2
  }
])
const orgData = ref([])
//新增
const form = reactive({
  files: [],
  title: undefined,
  org: [],
  documentNum: undefined,
  describes: undefined,
  year: undefined,
  dataSource: undefined,
  effective: undefined
})

//保存草稿
const saveTheDraft = () => {
  let detailDO = detailInfo.value.detailDO
  let files = form.files
    .filter((i) => i.isSave)
    .map((i) => {
      let file = {
        fileName: '',
        filePage: i.fileSum,
        fileUrl: ''
      }
      if (Array.isArray(i.file) && i.file.length > 0) {
        //上传了文件
        file.fileName = i.name
        file.fileUrl = i.file[0].url
      }
      return file
    })
  let data = {
    draft: JSON.stringify({ ...form, files, detailDO }),
    sorgResultPublicityId: tabListValue.value
  }
  msgDraft(data).then((res) => {
    isEdit.value = isEdit.value === 1 ? 0 : 1
    reloadDetail()
  })
}

const save = () => {
  let detailDO = []
  if (detailInfo.value.source === 1) {
    detailDO = detailInfo.value.detailDO.filter((i) => {
      let status = false
      let currentInfo = detailInfoOld.value.detailDO.find(
        (j) => j.sorgResultPublicityDetailId === i.sorgResultPublicityDetailId
      )
      if (currentInfo.handle != i.handle) {
        status = true
      }
      if (currentInfo.rectFlag != i.rectFlag) {
        status = true
      }
      if (currentInfo.law != i.law) {
        status = true
      }

      return status
    })
  }
  let files = form.files
    .filter((i) => i.isSave)
    .map((i) => {
      let file = {
        fileName: '',
        filePage: i.fileSum,
        fileUrl: ''
      }
      if (Array.isArray(i.file) && i.file.length > 0) {
        //上传了文件
        file.fileName = i.name
        file.fileUrl = i.file[0].url
      }
      return file
    })
  let data = {
    ...form,
    files,
    sorgResultPublicityId: tabListValue.value,
    detailList: detailDO,
    draft: null
  }
  console.log('form', data, form)

  msgAddOrUpd(data).then(async (res) => {
    ElMessage.success('保存成功！')
    params.value.pageNum = 1
    isEdit.value = 0
    init(true)
  })
}

//发布
const publish = () => {
  ElMessageBox.confirm('确定进行发布操作？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      msgRelease({ sorgResultPublicityId: tabListValue.value }).then((res) => {
        ElMessage.success('发布成功！')
        reloadDetail()
      })
    })
    .catch(() => {})
}

//生成台账
const generateLedgers = () => {
  msgLedger({ id: tabListValue.value }).then((res) => {
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const a = document.createElement('a')
    const URL = window.URL || window.webkitURL
    const herf = URL.createObjectURL(blob)
    a.href = herf
    a.download = '消息公开.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(herf)
  })
}
</script>
<style lang="scss" scoped>
:deep(.el-card__body) {
  padding: 0;
}
.box {
  display: flex;
  width: 100%;
  height: calc(100vh - 210px);
  position: relative;
  .box-tab {
    width: 450px;
    height: 100%;
    border-right: 1px solid #e1e1e1;
    position: relative;
    .scrollbar {
      height: calc(100% - 150px);
    }
    .box-tab-search {
      width: 100%;
      display: flex;
      justify-content: space-around;
      padding: 20px;
      box-sizing: border-box;
      & > div {
        display: flex;
        align-items: center;
        width: 100%;
        span {
          margin-right: 27px;
        }
        .select {
          width: 106px;
        }
      }
    }
    .box-tab-list {
      width: 100%;
      padding: 0 20px 0px 30px;
      box-sizing: border-box;
      .box-tab-list-item {
        width: 100%;
        margin-bottom: 20px;
        border-radius: 0px 0px 0px 0px;
        border: 1px solid #e9e9e9;
        box-sizing: border-box;
        padding: 20px 20px 0 20px;
        cursor: pointer;
        .box-tab-list-item-title {
          font-family: 思源黑体 CN, 思源黑体 CN;
          font-weight: bold;
          font-size: 18px;
          color: #333333;
          border-bottom: 1px solid #e9e9e9;
          padding-bottom: 11px;
        }
        .box-tab-list-item-time {
          font-family: 思源黑体 CN, 思源黑体 CN;
          font-weight: 400;
          font-size: 18px;
          color: #333333;
          padding: 11px 0;
        }
      }
      .box-tab-list-item-ac {
        position: relative;
      }
      .box-tab-list-item-ac::before {
        content: '';
        width: 4px;
        height: 100%;
        background: #1c85ff;
        border-radius: 0px 0px 0px 0px;
        position: absolute;
        left: -2px;
        top: 0;
        z-index: 2;
      }
    }
    .box-tab-add {
      width: 100%;
      position: absolute;
      height: 78px;
      display: flex;
      justify-content: center;
      align-items: center;
      bottom: 0;
      left: 0;
      background: white;
      z-index: 9;
      border-top: 1px solid #e9e9e9;
      div {
        cursor: pointer;
        width: 400px;
        height: 38px;
        background: #1c85ff;
        border-radius: 0px 0px 0px 0px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        font-size: 15px;
        color: #ffffff;
      }
    }
  }
  .box-content {
    flex: 1;
    min-width: 0;
    .box-content-header {
      width: 100%;
      padding: 20px 18px 20px 30px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e9e9e9;
      .box-content-header-title {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        font-size: 18px;
        color: #333333;
      }
      .box-content-header-btns {
        display: flex;
      }
    }
  }
}

.info {
  display: flex;
  margin-bottom: 20px;
  padding-top: 20px;
  .info-label {
    width: 108px;
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 300;
    font-size: 18px;
    color: #666666;
    margin-right: 20px;
    display: inline-flex;
    justify-content: flex-end;
    align-items: center;
    height: 30px;
  }
  .info-input {
    flex: 1;
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 400;
    font-size: 18px;
    color: #333333;
    line-height: 30px;
    min-width: 0;
  }
}

.upload {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.uploadListTable {
  border: 1px solid #e9e9e9;
}

:deep(.uploadListTable th) {
  background: #f5f6f8;
  font-weight: 300;
  font-size: 16px;
  color: #333333;
  height: 38px;
}

:deep(.el-col) {
  border-bottom: 1px solid #e9e9e9;
}

.table {
  width: 100%;
  padding: 50px 0;
  .table-title {
    font-weight: 500;
    font-size: 26px;
    color: #333333;
    text-align: center;
    margin-bottom: 30px;
  }

  table {
    border-collapse: collapse;
    width: 100%;
    margin-top: 8px;
  }

  th,
  td {
    border: 1px solid #000;
    padding: 6px;
    height: 39px;
    text-align: center;
    font-size: 14px;
    :deep(.el-input) {
      --el-input-border-color: none;
      width: 100% !important;
    }
    :deep(.el-date-editor) {
      width: 90% !important;
    }
    :deep(.el-textarea__inner) {
      height: 100% !important;
    }
    .el-input-number {
      width: 100% !important;
    }
    :deep(.el-input__prefix-inner) {
      display: none;
    }
  }

  th {
    background-color: #f2f2f2;
  }
}
.btns {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px 20px 0;
  border-top: 1px solid #e9e9e9;
}
.select {
  width: 480px;
}
.content {
  width: 100%;
  box-sizing: border-box;
  padding: 30px 18px 0 30px;
  height: calc(100% - 60px);
  overflow-y: scroll;
}
.header {
  display: flex;
  align-items: center;
  .icon {
    margin-right: 16px;
    cursor: pointer;
  }
  span {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 500;
    font-size: 20px;
    color: #333333;
  }
}
</style>
